#include "SettingsView.h"

using namespace std;

int SettingsView::filledColumns = 0;

SettingsView::SettingsView(QWidget * parent) : QWidget(parent)
{
	ui.setupUi(this);

	_currentRow = 0;

	/// komorki tabeli beda klikalne, ale nieedytowalne
	ui.parametersTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

	/// connect odpowiedzialny za aktywowanie przyciskow po wybraniu liczby pikow
	connect(ui.peaksEdit, SIGNAL(editingFinished()), this, SLOT(enableControls()));

	/// connect odpowiedzialny za wprowadzenie to tabeli zadanej liczby wierszy
	connect(ui.peaksEdit, SIGNAL(editingFinished()), this, SLOT(addRow()));

	ui.parametersTable->installEventFilter(this);
}

void SettingsView::SetModel(SettingsModel *model)
{
	_model = model;
}

void SettingsView::displayParameter(const QPointF &point)
{
	const vector<QPointF> parametersVector = _model->getParamters();
	
	QTableWidgetItem *tableItem = new QTableWidgetItem();

	///TODO : nie mam narazie lepszego pomyslu
	if(filledColumns == 3)
	{
		filledColumns = 0;
		_currentRow++;
	}
	ui.parametersTable->setItem(_currentRow, filledColumns, tableItem);

	tableItem->setText(QString(QString::number(parametersVector.back().x())+" , "+QString::number(parametersVector.back().y())));	

	filledColumns++;

	ui.parametersTable->setCurrentItem(tableItem);

	if(ui.parametersTable->currentItem()->column() == 2 && ui.parametersTable->currentItem()->row() == _numberOfPeaks-1)
	{	
		filledColumns = _currentRow = 0;
		emit fitDataLoaded();
	}
}

void SettingsView::addRow()
{
	_numberOfPeaks = ui.peaksEdit->text().toInt();
	ui.parametersTable->setRowCount(_numberOfPeaks);
}

void SettingsView::enableControls()
{
	/// guzik do wczytywania parametrow wykresu - stary przedzial ufnosci
	ui.plotParametersButton->setEnabled(true);
}

void SettingsView::enableFitOptions(const bool flag)
{
	ui.fitTypeComboBox->setEnabled(flag);

	ui.peaksEdit->setEnabled(flag);

	ui.plotParametersButton->setEnabled(false);
}

void SettingsView::resetFitParameters()
{
	ui.parametersTable->setRowCount(0);
	
	ui.peaksEdit->clear();

	filledColumns = 0;
	_currentRow = 0;

}

bool SettingsView::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyPress) 
	{
		QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

		if( keyEvent->key() == 45) /// kod klawisza minus
		{
			QList<QTableWidgetItem *> highlightedRow = ui.parametersTable->selectedItems();

			if(highlightedRow.size() !=0)
			{
			ui.parametersTable->removeRow(highlightedRow.at(0)->row());
			
			//TODO : to dla tych duzych plikow bedzie odblokowane
			///enableFitOptions(true);
			}	
        return true;
		}
    } 
	else 
        return QObject::eventFilter(obj, event);
    
}